/*
 * OpenList.cpp
 *
 *  Created on: 29/05/2011
 *      Author: frandres
 */

#include "OpenList.h"

OpenList::OpenList()
{

	for (int i = 0; i < LIST_SIZE; ++i) {
		lists[i] = new BinaryHeap();
	}
}

OpenList::~OpenList()
{
	for (int i = 0; i < LIST_SIZE; ++i) {
		delete(lists[i]);
	}
}

int OpenList::size(){
	int size =0;
	for (int i = 0; i < LIST_SIZE; ++i) {
		size+=lists[i]->size();
	}

	return size;
}
void OpenList::insert(FifteenPuzzleNodeA * element)
{
	lists[element->getF()]->insertElement(element);
}

void OpenList::remove(FifteenPuzzleNodeA * element)
{
	lists[element->getF()]->removeElement(element->getHeapIndex());
}

void OpenList::changeCost(FifteenPuzzleNodeA * element, int newG)
{
	lists[element->getF()]->removeElement(element->getHeapIndex());
	element->setG(newG);
	lists[element->getF()]->insertElement(element);
}

FifteenPuzzleNodeA *OpenList::pullMax()
{
	for(int i = 0; i < LIST_SIZE; i++)
		if(!lists[i]->empty())
			return lists[i]->pullMax();

	return NULL;

}

bool OpenList::find(FifteenPuzzleNodeA * element)
{
	for(int i = 0; i < ((int)lists[element->getF()]->elements->size()); i++)
	{


		int board1[16];
		int board2[16];
		bool aja = false;

		lists[element->getF()]->elements->operator [](i)->getBoard(board1);
		element->getBoard(board2);

		for(int j = 0; j < 16; j++)
			if(board1[j] != board2[j])
			{
				aja = true;
				break;
			}

		if(aja)
			continue;

		if(lists[element->getF()]->elements->operator [](i)->getG() != element->getG())
			continue;

		if(lists[element->getF()]->elements->operator [](i)->getH() != element->getH())
			continue;

		if(lists[element->getF()]->elements->operator [](i)->getFatherMovements() != element->getFatherMovements())
			continue;

		return true;
	}

	return false;
}
